package com.gzdh.dishrecognition.ui.dialog.identify;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.blankj.utilcode.util.StringUtils;
import com.dhkj.web.idf.IdfTagRequestUtils;
import com.dhkj.web.idf.model.DeviceLoginWraper;
import com.dhkj.web.idf.model.LoginWraper;
import com.dhkj.web.utils.MyObserverNo;
import com.gzdh.dishrecognition.R;
import com.gzdh.dishrecognition.util.SdcardUtils;

public class LoginFragment extends DialogFragment {
    private static final String TAG = "LoginFragment";
    private Context mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        setRetainInstance(true);
//        systemSettingObject = getArguments().getParcelable(SystemSettingDialogFragment.SYSTEM_SETTING);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContext = inflater.getContext();
        View view = getViews();
        getDialog().getWindow().getDecorView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                InputMethodManager manager = (InputMethodManager)getActivity()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (getDialog().getCurrentFocus() != null
                            && getDialog().getCurrentFocus().getWindowToken() != null) {
                        manager.hideSoftInputFromWindow(getDialog().getCurrentFocus()
                                .getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                return false;
            }
        });
        return view;
    }

    private EditText userNameEd;

    private EditText passwordEd;

    private View getViews() {
        RelativeLayout relativeLayout = new RelativeLayout(mContext);
        relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        LinearLayout linearLayout = new LinearLayout(mContext);
        LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(500, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearLayout.setLayoutParams(linearParams);
        linearLayout.setGravity(Gravity.CENTER);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setPadding(20, 30, 20, 30);
        relativeLayout.addView(linearLayout);


        //region 账号
        RelativeLayout userNameRv = new RelativeLayout(mContext);
        linearParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearParams.setMargins(40, 20, 40, 0);
        userNameRv.setLayoutParams(linearParams);
        linearLayout.addView(userNameRv);


        ImageView userIconName = new ImageView(mContext);
        userIconName.setId(View.generateViewId());
        RelativeLayout.LayoutParams rvParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        rvParams.addRule(RelativeLayout.CENTER_VERTICAL);
        userIconName.setLayoutParams(rvParams);
        userIconName.setPadding(10, 5, 0, 5);
        userIconName.setImageBitmap(drawableToBitmap(getResources().getDrawable(R.mipmap.login_zhanghao)));
        userNameRv.addView(userIconName);


        View viewName = new View(mContext);
        viewName.setId(View.generateViewId());
        rvParams = new RelativeLayout.LayoutParams(5, 15);
        rvParams.addRule(RelativeLayout.CENTER_VERTICAL);
        rvParams.addRule(RelativeLayout.RIGHT_OF, userIconName.getId());
        rvParams.setMargins(10, 0, 0, 0);
        viewName.setLayoutParams(rvParams);
        viewName.setBackgroundColor(Color.rgb(200, 200, 200));
        userNameRv.addView(viewName);

        userNameEd = new EditText(mContext);
        rvParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50);
        rvParams.addRule(RelativeLayout.CENTER_VERTICAL);
        rvParams.setMargins(10, 0, 0, 0);
        rvParams.addRule(RelativeLayout.RIGHT_OF, viewName.getId());
        userNameEd.setLayoutParams(rvParams);
        userNameEd.setBackground(null);
        userNameEd.setHint("用户名");
        userNameEd.setEms(19);
        userNameEd.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        userNameRv.addView(userNameEd);
        //endregion


        RelativeLayout passwordRv = new RelativeLayout(mContext);
        linearParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearParams.setMargins(40, 20, 40, 0);
        passwordRv.setLayoutParams(linearParams);
        linearLayout.addView(passwordRv);


        ImageView passwordIconName = new ImageView(mContext);
        passwordIconName.setId(View.generateViewId());
        rvParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        rvParams.addRule(RelativeLayout.CENTER_VERTICAL);
        passwordIconName.setLayoutParams(rvParams);
        passwordIconName.setPadding(10, 5, 0, 5);
        passwordIconName.setImageBitmap(drawableToBitmap(getResources().getDrawable(R.mipmap.login_mima)));
        passwordRv.addView(passwordIconName);


        View viewPassword = new View(mContext);
        viewPassword.setId(View.generateViewId());
        rvParams = new RelativeLayout.LayoutParams(5, 15);
        rvParams.addRule(RelativeLayout.CENTER_VERTICAL);
        rvParams.addRule(RelativeLayout.RIGHT_OF, passwordIconName.getId());
        rvParams.setMargins(10, 0, 0, 0);
        viewPassword.setLayoutParams(rvParams);
        viewPassword.setBackgroundColor(Color.rgb(200, 200, 200));
        passwordRv.addView(viewPassword);

        passwordEd = new EditText(mContext);
        rvParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50);
        rvParams.addRule(RelativeLayout.CENTER_VERTICAL);
        rvParams.setMargins(10, 0, 0, 0);
        rvParams.addRule(RelativeLayout.RIGHT_OF, viewPassword.getId());
        passwordEd.setLayoutParams(rvParams);
        passwordEd.setBackground(null);
        passwordEd.setHint("密码");
        passwordEd.setEms(19);
        passwordEd.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        passwordRv.addView(passwordEd);

        Button submitBut = new Button(mContext);

        rvParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50);
        rvParams.setMargins(50, 0, 40, 40);
        submitBut.setText("登录");
        submitBut.setGravity(Gravity.CENTER);
        submitBut.setTextColor(Color.WHITE);
        submitBut.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        submitBut.setBackground(getResources().getDrawable(R.drawable.bg_btn_pay));
        linearLayout.addView(submitBut);
        submitBut.setOnClickListener(view -> preLogin());
        return relativeLayout;
    }


    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    private void preLogin() {
        String registrationNumber = SdcardUtils.getRegistrationNumber();
        if (StringUtils.isEmpty(registrationNumber)) {
            Toast.makeText(mContext, "设备尚未激活，请先激活再试一下", Toast.LENGTH_SHORT).show();
            return;
        }
        IdfTagRequestUtils.deviceLogin(mContext, registrationNumber, new MyObserverNo<DeviceLoginWraper>(mContext) {
            @Override
            public void onSuccess(DeviceLoginWraper result) {
                if (result.getState() == 200) {
                    login(result);
                } else if (result.getResult().getState() == 620) {
                    Toast.makeText(mContext, "设备激活失败，请检查激活", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext, "其他错误#101", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {

            }
        });
    }

    private void login(DeviceLoginWraper deviceLoginWraper) {
        IdfTagRequestUtils.login(mContext, userNameEd.getText().toString(), passwordEd.getText().toString(), deviceLoginWraper.getResult().getDevicePK(),
                new MyObserverNo<LoginWraper>(mContext) {
                    @Override
                    public void onSuccess(LoginWraper result) {
                        if (result.getState() == 310) {
                            Toast.makeText(mContext, result.getMsg(), Toast.LENGTH_SHORT).show();
                        } else if (result.getState() == 200) {
//                            if (result.getResult() != null) {
//                                result.getResult().setPassword(password);
//                                storageInteractor.setUser(loginWraper.getResult());
//                                if (view != null)
//                                    view.loginSuccessForward();
//                            }
                            Toast.makeText(mContext, "登录成功", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {

                    }
                });
    }


    /**
     * 根据传入控件的坐标和用户的焦点坐标，判断是否隐藏键盘，如果点击的位置在控件内，则不隐藏键盘
     *
     * @param view  控件view
     * @param event 焦点位置
     * @return 是否隐藏
     */
    public static void hideKeyboard(MotionEvent event, View view, Activity activity) {
        try {
            if (view instanceof EditText) {
                int[] location = {0, 0};
                view.getLocationInWindow(location);
                int left = location[0], top = location[1], right = left
                        + view.getWidth(), bootom = top + view.getHeight();
                // （判断是不是EditText获得焦点）判断焦点位置坐标是否在控件所在区域内，如果位置在控件区域外，则隐藏键盘
                if (event.getRawX() < left || event.getRawX() > right || event.getY() < top || event.getRawY() > bootom) {
                    // 隐藏键盘
                    IBinder token = view.getWindowToken();
                    InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏软键盘
     *
     * @param view :一般为EditText
     */
    public static void hideKeyboard(View view) {
        InputMethodManager manager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        //获取当前获得焦点的View
//        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//            View view = getCurrentFocus();
//            //调用方法判断是否需要隐藏键盘
//            KeyboardUtils.hideKeyboard(ev, view, this);
//        }
//        return super.dispatchTouchEvent(ev);
//    }
}
